package com.plugin.uniapp.video;

public class BitReader {
    private byte[] data;
    private int byteOffset = 0;
    private int bitOffset = 0;

    public BitReader(byte[] data) {
        this.data = data;
    }

    public int readBit() {
        int value = (data[byteOffset] >> (7 - bitOffset)) & 0x01;
        bitOffset++;
        if (bitOffset == 8) {
            bitOffset = 0;
            byteOffset++;
        }
        return value;
    }

    public int readBits(int n) {
        int val = 0;
        for (int i = 0; i < n; i++) {
            val = (val << 1) | readBit();
        }
        return val;
    }

    public void skipBits(int n) {
        for (int i = 0; i < n; i++) {
            readBit();
        }
    }

    public int readUE() {
        int zeros = 0;
        while (readBit() == 0 && zeros < 32) zeros++;
        int value = (1 << zeros) - 1 + readBits(zeros);
        return value;
    }

    public int readSE() {
        int codeNum = readUE();
        int val = (codeNum + 1) >> 1;
        return (codeNum & 1) == 0 ? -val : val;
    }
}